<?php
/*
 * @Descripttion: 管理员账号管理
 * @version:
 * @Author: ewgof
 * @Date: 2019-11-01 09:59:22
 * @LastEditors: ewgof
 * @LastEditTime: 2020-10-04 21:52:51
 */
namespace app\http\controller\admin;

class Admin extends Base
{
    public function index($request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 15);
        $num = ($page - 1) * $limit;
        // 搜索类目:username status
        $status = $request->get('status');     // 状态，0：全部，1：正常，2：禁用
        $keywords = $request->get('keywords');
        // halt($keywords);

        $where = [];
        if (!empty($keywords)) {
            $where['username[~]'] = $keywords;
        }
        if (!empty($status)) {
            $where['status'] = $status;
        }

        $where['ORDER'] = ['created_at' => 'DESC', 'updated_at' => 'DESC'];
        $where['LIMIT'] = [$num, $num + $limit];

        $all = $this->db->count('admins', $where);
        $list = $this->db->select('admins', ['id', 'username', 'status', 'created_at', 'updated_at'], $where);
        $info = array(
            'all' => $all,
            'list' => $list,
        );
        // halt($admin_info);
        return api_json_return(0, '', $info);
    }

    /**
     * @name:
     * @msg: 添加后台管理员，默认密码 1234567aa
     * @param $phone string
     * @param $username string 用户名，用于登录后台
     * @param $role integer 角色id
     * @return:
     */
    public function create($request)
    {
        $input = $request->post();
        $username = $input['username'];
        $passwd = $input['password'];

        if (empty($username)) {
            return api_json_return(20001);
        }
        if (empty($passwd)) {
            return api_json_return(20002);
        }
        $result = validate('app\common\validate\Login.admin_login', $input);
        if ($result !== true) {
            return api_json_return(1, $result);
        }

        // 判断管理员是否已经存在
        if (!empty($this->db->get('admins', 'id', ['username' => $username]))) {
            return api_json_return(10012);
        }

        $data = array(
            'username' => $username,
            'password' => password_hash($passwd, PASSWORD_DEFAULT),
            'status' => 1,
            'picture' => 'http://' . $request->host() . '/upload/default/default_admin_avatar.jpg',
            'updated_at' => $this->t,
            'created_at' => $this->t,
        );
        $info = $this->db->insert('admins', $data)->rowCount();
        if ($info === 1) {
            return api_json_return(0);
        } else {
            return api_json_return(1);
        }
    }


    public function edit($request)
    {
        $id = $request->get('id');
        if (empty($id)) {
            return api_json_return(2);
        }

        $ad_info = $this->db->get('admins', ['id', 'username', 'status'], ['id' => $id]);
        return api_json_return(0, '', $ad_info);
    }


    /**
     * @name: update
     * @msg:
     * @param {type}
     * @return:
     */
    public function update($request)
    {
        $username = $request->post('username', '');
        $password = $request->post('password', '');
        $status = $request->post('status', 0);
        $id = $request->post('id');
        if (empty($id)) {
            return api_json_return(2);
        }

        if (!empty($username)) {
            if (\mb_strlen($username) < 2 || \mb_strlen($username) > 50) {
                return api_json_return(10009);
            }
            $data['username'] = $username;
        }
        if (!empty($password)) {
            if (!preg_match(PASSWORD_REG, $password)) {
                return api_json_return(10011);
            }
            $data['password'] = password_hash($password, PASSWORD_DEFAULT);
        }
        if (!empty($status)) {
            $ad_token = $this->db->get('admins', 'token', ['id' => $id]);
            if ($ad_token == $request->header('token')) {
                return api_json_return(20005);
            }
            $data['status'] = $status;
        }
        if (empty($data)) {
            return api_json_return(18);
        }
        $info = $this->db->update('admins', $data, ['id' => $id])->rowCount();
        if ($info === 1) {
            return api_json_return(0);
        } elseif ($info === 0) {
            return api_json_return(18);
        } else {
            $msg = '更新管理员数据失败。id => '.$id.', info => '.$info;
            echo $msg . PHP_EOL;
            log_msg($msg, 'apperr', $this->log_filename_apperr);
            return api_json_return(1);
        }
    }

    /**
     * @name: delete
     * @msg: 删除管理员
     * @param $id integer 被删除管理员id
     * @return:
     */
    public function delete($request)
    {
        $id = $request->post('id');
        if (empty($id)) {
            return api_json_return(2);
        }
        $token = $request->header('token');
        
        $ad_info = $this->db->get('admins', ['id', 'token', 'status', 'username'], ['id' => $id]);
        // halt($admin_info);
        // 不能删除自己
        if ($token == $ad_info['token']) {
            return api_json_return(20003);
        }
        // 未停用账号不可删除
        if ($ad_info['status'] != 2) {
            return api_json_return(20004);
        }

        $info = $this->db->delete('admins', ['id' => $id])->rowCount();
        if ($info) {
            return api_json_return(0);
        } else {
            $msg = '删除管理员失败。当前登录管理员 token => '.$token.', 被删除管理员信息： id => '.$id.', username => '.$ad_info['username'].', info => '.$info;
            log_msg($msg, 'apperr', $this->log_filename_apperr);
            echo $msg . PHP_EOL;
            return api_json_return(1);
        }
    }
}
